//
//  MapNavigationViewController.m
//  LiTianDecoration
//
//  Created by zero on 2018/7/24.
//  Copyright © 2018年 administrator. All rights reserved.
//
#define DefaultLocationTimeout  6
#define DefaultReGeocodeTimeout 3

#define CURRENT_SIZE(_size) _size / 375.0 * KScreenWidth

#import "MapNavigationViewController.h"
#import "CusAnnotationView.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>

#import <AMapSearchKit/AMapSearchKit.h>
#import "MANaviRoute.h"
#import "CommonUtility.h"
#import "ErrorInfoUtility.h"

static const NSString *RoutePlanningViewControllerStartTitle       = @"起点";
static const NSString *RoutePlanningViewControllerDestinationTitle = @"终点";
static const NSInteger RoutePlanningPaddingEdge                    = 20;

@interface MapNavigationViewController ()<MAMapViewDelegate, AMapLocationManagerDelegate,AMapSearchDelegate>

@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
///定位管理
@property (nonatomic, strong) AMapLocationManager *locationManager;
///地图
@property (weak, nonatomic) IBOutlet MAMapView *mapView;
///是否显示路线
@property (nonatomic,assign) BOOL isbool;
///** 轨迹纠偏 */
//@property (nonatomic, strong) MATraceManager * traceManager;

/* 起点经纬度. */
@property (nonatomic) CLLocationCoordinate2D                              startCoordinate;
/* 终点经纬度. */
@property (nonatomic) CLLocationCoordinate2D                              destinationCoordinate;

@property (nonatomic, strong) MAPointAnnotation                         * startAnnotation;
@property (nonatomic, strong) MAPointAnnotation                         * destinationAnnotation;
/* 用于显示当前路线方案. */
@property (nonatomic) MANaviRoute * naviRoute;
///线路规划
@property (nonatomic,strong) AMapSearchAPI *searchAPI;
@property (nonatomic, strong) AMapRoute *route;

/* 当前路线方案索引值. */
@property (nonatomic) NSInteger currentCourse;
///其实城市
@property (nonatomic,copy) NSString *start_city;


@end

@implementation MapNavigationViewController



- (void)viewDidLoad
{
    [super viewDidLoad];

        self.title = @"门店地图";
        [self SetUI];
    
        [self initCompleteBlock];
        [self configLocationManager];
        [self locAction];
        [self Add_Annotation];
    
    
}
/**
 设置地图
 */
- (void)SetUI
{
    
    _isbool = NO;
    _mapView.showsCompass = NO;
    _mapView.showsScale = NO;
    _mapView.delegate = self;
    _mapView.touchPOIEnabled = NO;
    
    _searchAPI = [[AMapSearchAPI alloc] init];
    _searchAPI.delegate = self;
    
    [self.mapView setZoomLevel:12.0 animated:NO];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"显示路线" style:UIBarButtonItemStyleDone target:self action:@selector(isboolAction)];
}
///是否显示路线事件
- (void)isboolAction
{
    _isbool = !_isbool;
  
    [self.mapView removeAnnotations:self.mapView.annotations];
    [self.naviRoute removeFromMapView];
   
    if (_isbool){
        [self searchRoutePlanningBusCrossCity];
    }else{
        [self Add_Annotation];
    }
}
#pragma mark - do search
- (void)searchRoutePlanningBusCrossCity
{
    [self addDefaultAnnotations];
    
    self.startAnnotation.coordinate = self.startCoordinate;
    self.destinationAnnotation.coordinate = self.destinationCoordinate;
    
    AMapTransitRouteSearchRequest *navi = [[AMapTransitRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    navi.city             = self.model.areaInfo;
//    navi.destinationCity  = self.model.areaInfo;
    
    /* 出发点. */
    navi.origin = [AMapGeoPoint locationWithLatitude:self.startAnnotation.coordinate.latitude
                                           longitude:self.startAnnotation.coordinate.longitude];
    /* 目的地. */
    navi.destination = [AMapGeoPoint locationWithLatitude:self.destinationAnnotation.coordinate.latitude
                                                longitude:self.destinationAnnotation.coordinate.longitude];
    
    [self.searchAPI AMapTransitRouteSearch:navi];
}

#pragma mark  -----------------------店铺位置信息展示---------------------------
/**
 添加大头针
 */
- (void)Add_Annotation
{
    MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
    [annotation setCoordinate:CLLocationCoordinate2DMake(_model.lat, _model.lng)];
    [self addAnnotationToMapView:annotation];
}

///创建定位管理者
- (void)configLocationManager
{
    self.locationManager = [[AMapLocationManager alloc] init];
    [self.locationManager setDelegate:self];
    //设置期望定位精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //设置不允许系统暂停定位
    [self.locationManager setPausesLocationUpdatesAutomatically:NO];
    //设置允许在后台定位
    [self.locationManager setAllowsBackgroundLocationUpdates:YES];
    //设置定位超时时间
    [self.locationManager setLocationTimeout:DefaultLocationTimeout];
    //设置开启虚拟定位风险监测，可以根据需要开启
    [self.locationManager setDetectRiskOfFakeLocation:NO];
}

- (void)cleanUpAction
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
    
    [self.locationManager setDelegate:nil];
    
    [self.mapView removeAnnotations:self.mapView.annotations];
}
- (void)locAction
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    //进行单次定位请求
    [self.locationManager requestLocationWithReGeocode:NO completionBlock:self.completionBlock];
    
}


#pragma mark - Initialization

- (void)initCompleteBlock
{
    __weak MapNavigationViewController *weakSelf = self;
    self.completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
        {
            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else
        {
            weakSelf.startCoordinate = CLLocationCoordinate2DMake(39.056581, 117.127697);
            weakSelf.destinationCoordinate = CLLocationCoordinate2DMake(weakSelf.model.lat, weakSelf.model.lng);
            weakSelf.start_city = regeocode.city;
    
        }
    };
}


- (void)addAnnotationToMapView:(id<MAAnnotation>)annotation
{
    [self.mapView addAnnotation:annotation];
    
    [self.mapView selectAnnotation:annotation animated:NO];
    
    [self.mapView setCenterCoordinate:annotation.coordinate animated:NO];
}
#pragma mark  -----------------------店铺位置信息展示---------------------------

#pragma mark - MAMapView Delegate

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]]){

        static NSString *customReuseIndetifier = @"customReuseIndetifier";
        CusAnnotationView *annotationView = (CusAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];
        
        if (annotationView == nil)
        {
            annotationView = [[CusAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, 0);
        }
        annotationView.model = _model;
       
        if (_isbool) {
        
            if ([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerStartTitle])
            {
                annotationView.image = [UIImage imageNamed:@"起点icon"];
                //设置中心点偏移，使得标注底部中间点成为经纬度对应点
                annotationView.centerOffset = CGPointMake(0, -(CURRENT_SIZE(24)/2));
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerDestinationTitle])
            {
                annotationView.image = [UIImage imageNamed:@"终点icon"];
                //设置中心点偏移，使得标注底部中间点成为经纬度对应点
                annotationView.centerOffset = CGPointMake(0, -(CURRENT_SIZE(24)/2));
                
            }
        }else{
               annotationView.portrait = [UIImage imageNamed:@"ico_ditu"];
        }
        return annotationView;
        
    }
    
    
    return nil;
}
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view
{

    view.selected = !_isbool;
}

#pragma mark ------------------添加规划路线-------------------

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];

        polylineRenderer.lineWidth = 8;
        
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = [UIColor redColor];
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = [UIColor redColor];
        }
        else
        {
            polylineRenderer.strokeColor = [UIColor redColor];
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 8;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        
        return polylineRenderer;
    }
    
    return nil;
}

#pragma mark -------------------- 轨迹纠偏 --------------------




- (void)addDefaultAnnotations
{
    MAPointAnnotation *startAnnotation = [[MAPointAnnotation alloc] init];
    startAnnotation.coordinate = self.startCoordinate;
    startAnnotation.title      = (NSString*)RoutePlanningViewControllerStartTitle;
    startAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.startCoordinate.latitude, self.startCoordinate.longitude];
    self.startAnnotation = startAnnotation;
    
    MAPointAnnotation *destinationAnnotation = [[MAPointAnnotation alloc] init];
    destinationAnnotation.coordinate = self.destinationCoordinate;
    destinationAnnotation.title      = (NSString*)RoutePlanningViewControllerDestinationTitle;
    destinationAnnotation.subtitle   = [NSString stringWithFormat:@"{%f, %f}", self.destinationCoordinate.latitude, self.destinationCoordinate.longitude];
    self.destinationAnnotation = destinationAnnotation;
    
    [self.mapView addAnnotation:startAnnotation];
    [self.mapView addAnnotation:destinationAnnotation];
}
/* 展示当前路线方案. */
- (void)presentCurrentCourse
{
    self.naviRoute = [MANaviRoute naviRouteForTransit:self.route.transits[self.currentCourse] startPoint:[AMapGeoPoint locationWithLatitude:self.startAnnotation.coordinate.latitude longitude:self.startAnnotation.coordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destinationAnnotation.coordinate.latitude longitude:self.destinationAnnotation.coordinate.longitude]];
    [self.naviRoute addToMapView:self.mapView];
    
    /* 缩放地图使其适应polylines的展示. */
    [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines]
                        edgePadding:UIEdgeInsetsMake(RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge, RoutePlanningPaddingEdge)
                           animated:NO];
}
/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    self.route = response.route;
    if (response.count > 0)
    {
        [self presentCurrentCourse];
    }
    
    //解析response获取路径信息，具体解析见 Demo
}
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@", [ErrorInfoUtility errorDescriptionWithCode:error.code]);
}
#pragma mark -------------------- 轨迹纠偏 --------------------


- (void)dealloc
{
    [self cleanUpAction];
    self.completionBlock = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
